<template>

	<view class="main" :style="{height:wh+'px'}">
		<!-- 注册 -->
		<view class="content" v-if="flag">
			<view class="box">
				<block v-for="(item, i) in biaoti" :key="i">
					<view :class="[ 'qiehuan' ,i===active ? 'active' : '']" @click="qiehuan(i)">{{item.text}}</view>
				</block>
			</view>
			<uni-forms ref="zhuce" :rules="rules" :modelValue="zhuce">
				<uni-forms-item name="account">
					<uni-easyinput type="text" prefixIcon="email" v-model="zhuce.account" placeholder="请输入邮箱">
					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="password">
					<uni-easyinput prefixIcon="locked-filled" type="password" v-model="zhuce.password"
						placeholder="请输入密码"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="repassword">
					<uni-easyinput prefixIcon="locked-filled" type="password" v-model="zhuce.repassword"
						placeholder="确认密码"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="code">
					<view class="yz">
						<view class="input">
							<uni-easyinput v-model="zhuce.code" placeholder="请输入验证码"></uni-easyinput>
						</view>
						<view @click.stop="getcode('zhuce')" class="yzm" :style="{'color':getCodeBtnColor}">
							{{getcodetext}}
						</view>
					</view>
				</uni-forms-item>
			</uni-forms>
			<button class="button" type="primary" @click="zhucefn('zhuce')">注册</button>
		</view>
		<!-- 登录 -->
		<view class="content" v-else>

			<view class="box">
				<block v-for="(item, i) in biaoti" :key="i">
					<view :class="[ 'qiehuan' ,i===active ? 'active' : '']" @click="qiehuan(i)">{{item.text}}</view>
				</block>
			</view>
			<uni-forms ref="form" :rules="rules" :modelValue="user">
				<!-- name的名字要跟v-model的名字保持一致 -->
				<uni-forms-item name="name">
					<uni-easyinput type="text" prefixIcon="person" v-model="user.name" placeholder="请输入昵称">
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="account">
					<uni-easyinput type="text" prefixIcon="email" v-model="user.account" placeholder="请输入已注册邮箱">
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="password">
					<uni-easyinput prefixIcon="locked-filled" type="password" v-model="user.password"
						placeholder="请输入密码"></uni-easyinput>
				</uni-forms-item>
			</uni-forms>
			<button class="button" type="primary" @click="submitfn('form')">登录</button>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {
				//切换注册和登录
				biaoti: [{
					id: 1,
					text: "注册"
				}, {
					id: 2,
					text: "登录"
				}],
				flag: true,
				active: 0,

				//可用高度
				wh: 0,
				getcodetext: '获取验证码', //获取验证码
				getCodeBtnColor: "black", //发送验证码字体颜色
				getCodeisWaiting: false, //防止连续发送
				timer: null, // 定时器

				// 登录
				user: {
					// account: '1810649011@qq.com',
					// password: '123456',
					// name: '老谭'
				},
				// 注册
				zhuce: {
					//可以为空
					// account: '1810649011@qq.com',
					// code: '',
					// password: '123456',
					// repassword: '123456'
				},

				rules: {
					//校验邮箱
					account: {
						rules: [{
							required: true,
							errorMessage: '邮箱地址不能为空',
						}, {
							format: 'email',
							errorMessage: '请输入正确的邮箱地址',
						}],
						validateTrigger: 'submit'
					},
					//校验密码
					password: {
						//校验的规则
						rules: [{
							required: true,
							errorMessage: '密码不能为空',
						}, {
							minLength: 6,
							maxLength: 12,
							errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
						}],
						//点击按钮时校验
						validateTrigger: 'submit'
					},
					//校验确认密码
					repassword: {
						rules: [{
							required: true,
							errorMessage: '确认密码不能为空',
						}],
						validateTrigger: 'submit'
					},
					//注册时校验验证码
					code: {
						rules: [{
							format: 'number',
							errorMessage: '验证码只为数字'
						}],
						validateTrigger: 'submit'
					},
					//校验昵称
					name: {
						rules: [{
							required: true,
							errorMessage: '昵称不能为空',
						}],
						validateTrigger: 'submit'
					}
				}
			};
		},
		//页面加载
		onLoad() {

			// 获取当前系统的信息
			const sysInfo = uni.getWindowInfo()
			// 可用高度 = 屏幕高度 - navigationBar高度 - tabBar高度 - 自定义的search组件高度
			this.wh = sysInfo.windowHeight
		},
		computed: {
             ...mapState('m_user',['redirectInfo'])
		},
		methods: {
			...mapMutations('m_user', ['updataToken', 'updatauserinfo', 'updatauserjieshao', 'updateRedirectInfo']),
			//登录
			submitfn(ref) {
				this.$refs[ref].validate().then(res => {
					uni.request({
						url: 'https://api.apiopen.top/api/login',
						method: 'POST',
						data: this.user,
						success: (res) => {
							if (res.data.code !== 200) {
								return uni.$showMsg(res.data.message)
							} else {
								// console.log(res.data.result);
								//得到的token存储到vuex中
								this.updataToken(res.data.result.token)
								// 判断 vuex 中的 redirectInfo 是否为 null
								// 如果不为 null，则登录成功之后，需要重新导航到对应的页面
								this.navigateBack()
								//调用获取用户个人信息的方法
								this.getuserinfo(res.data.result)
								uni.showLoading({
									title: '登录中',
									mask: true
								});
								setTimeout(() => {
									uni.hideLoading();
									uni.$showMsg('登录成功')
								}, 1000);

							}

						}
					});

				}).catch(err => {
					console.log('err', err);
				})
			},
			//获取用户的个人信息
			getuserinfo(info) {

				//准备参数对象
				const querobj = {
					id: info.id,
					createdAt: info.createdAt,
					account: info.account,
					updatedAt: info.updatedAt,

				}
				// 将得到的用户信息存储到vuex中
				this.updatauserinfo(querobj)
				// 将得到的用户名字存储到user中
				const name = {
					name: this.user.name
				}
				this.updatauserjieshao(name)

			},
			//注册
			zhucefn(ref) {
				this.$refs[ref].validate().then(res => {
					uni.request({
						url: 'https://api.apiopen.top/api/register', //仅为示例，并非真实接口地址。
						method: 'POST',
						data: this.zhuce,
						success: (res) => {
							if (this.zhuce.code.trim() == '') return uni.$showMsg('验证码不能为空')
							if (this.zhuce.password.trim() !== this.zhuce.repassword.trim()) return uni
								.$showMsg('两次密码输入需一致')
							if (res.data.code !== 200) {
								return uni.$showMsg(res.data.message)
							} else {
								uni.$showMsg('注册成功')
								this.flag = !this.flag
							}

						}
					});
				}).catch(err => {
					console.log('err', err);
				})
			},

			//发送邮箱验证码
			getcode(ref) {
				this.$refs[ref].validate().then(res => {
					uni.request({
						url: 'https://api.apiopen.top/api/sendVerificationCode',
						method: 'POST',
						data: {
							mail: this.zhuce.account
						},
						success: (res) => {
							if (this.zhuce.password.trim() !== this.zhuce.repassword.trim()) return uni.$showMsg('两次密码输入需一致')
							if (res.data.code !== 200) return uni.$showMsg(res.data.message)
							uni.hideKeyboard() //隐藏已经显示的软键盘，如果软键盘没有显示则不做任何操作。
							if (this.getCodeisWaiting) {
								return;
							}
							this.getcodetext = "发送中...", //发送验证码
								this.getCodeisWaiting = true
							this.getCodeBtnColor = "#606266" //追加样式，修改颜色
							setTimeout(() => {
								uni.$showMsg('已发送验证码到邮箱');
								this.setTimer() //调用定时器方法
							}, 1000)
						}
					});
				}).catch(err => {
					console.log('err', err);
				})
			},
			//setTimer： 需要每隔一段时间执行一件事的的时候就需要使用SetTimer函数
			setTimer() {
				let holdTime = 60; //定义变量并赋值
				this.getcodetext = "重新获取(60)"
				//setInterval（）是一个实现定时调用的函数，可按照指定的周期（以毫秒计）来调用函数或计算表达式。
				//setInterval方法会不停地调用函数，直到 clearInterval被调用或窗口被关闭。
				clearInterval(this.timer)
				this.timer = setInterval(() => {
					if (holdTime <= 0) {
						this.getCodeisWaiting = false
						this.getCodeBtnColor = 'black'
						this.getcodetext = "获取验证码"
						clearInterval(this.timer); //清除该函数
						return;
					}
					this.getcodetext = "重新获取(" + holdTime + ")"
					holdTime--;
				}, 1000)
			},
			//切换登录和注册
			qiehuan(i) {
				this.active = i
				this.active === 0 ? this.flag = true : this.flag = false

			},
			// 返回登录之前的页面
			navigateBack() {
				// redirectInfo 不为 null，并且导航方式为 switchTab
				if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
					// 调用小程序提供的 uni.switchTab() API 进行页面的导航
					uni.switchTab({
						// 要导航到的页面地址
						url:this.redirectInfo.from,
						// 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
						complete:() =>{
							this.updateRedirectInfo(null)
						}
					})
				}
			}
		}

	}
</script>

<style lang="scss">
	.main {
		background: #7b7b7b;
		padding: 200rpx 0;
		width: 100%;
		position: relative;
		height: 100%;
	}

	.content {
		text-align: center;
		width: 80%;
		padding: 10rpx 20rpx;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 10px;
		position: absolute;
		left: 10%;

		.box {
			display: flex;
			justify-content: space-around;
			width: 100%;
			font-weight: bold;
			font-size: 20px;
			color: white;
			margin: 20px 0;
			white-space: nowrap;

			.qiehuan {
				padding-bottom: 7px;
				color: #7b7b7b;

				&.active {
					border-bottom: 2px solid white;
					color: white;
				}
			}
		}


		.button {
			width: 350rpx;
			height: 40px;
			line-height: 40px;
			background-color: orange;
			text-align: center;
			font-weight: bold;
			margin-bottom: 20px;

		}

		.yz {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.yzm {
				font-size: 12px;

				width: 80px;
				height: 41px;
				background-color: white;
				border-radius: 3px;
				text-align: center;
				line-height: 41px;
			}

			.input {
				flex: 1;
				margin-right: 10px;
			}
		}

		input {
			height: 40px;
		}

		.text {
			color: #7b7b7b;
			font-size: 12px;
			display: block;
			margin-bottom: 10px;
		}
	}
</style>
